import { Injectable, NestInterceptor, ExecutionContext, CallHandler, HttpStatus } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiResponseDto } from '../dto/api-response.dto';

@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, ApiResponseDto<T>> {
  intercept(context: ExecutionContext, next: CallHandler): Observable<ApiResponseDto<T>> {
    const response = context.switchToHttp().getResponse();
    
    return next.handle().pipe(
      map(data => {
        // 已经是标准格式的响应，直接返回
        if (data && data.code !== undefined && data.message !== undefined) {
          return data;
        }
        
        // 处理空数据
        if (data === null || data === undefined) {
          return ApiResponseDto.success(null);
        }
        
        // 获取HTTP状态码，并根据状态码设置不同的响应
        const statusCode = response.statusCode;
        
        if (statusCode === HttpStatus.CREATED) {
          return ApiResponseDto.created(data);
        }
        
        // 默认作为成功响应处理
        return ApiResponseDto.success(data);
      }),
    );
  }
} 